//
//  DZYNavigationController.m
//  DZYFM
//
//  Created by dongzhenyu on 2017/10/31.
//  Copyright © 2017年 dongzhenyu. All rights reserved.
//

#import "DZYNavigationController.h"
#import "DZYNavBar.h"
#import "DZYMiddleView.h"

@interface DZYNavigationController () <UIGestureRecognizerDelegate>

@end

@implementation DZYNavigationController

- (instancetype)initWithRootViewController:(UIViewController *)rootViewController
{
    if (self = [super initWithRootViewController:rootViewController]) {
        [self setValue:[DZYNavBar new] forKey:@"navigationBar"];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    UIGestureRecognizer *ges = self.interactivePopGestureRecognizer;
    
    UIPanGestureRecognizer *panGes = [[UIPanGestureRecognizer alloc] initWithTarget:ges.delegate action:NSSelectorFromString(@"handleNavigationTransition:")];
    [ges.view addGestureRecognizer:panGes];
    
    ges.delaysTouchesBegan = YES;
    panGes.delegate = self;
}

- (void)back
{
    [self popViewControllerAnimated:YES];
}

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    if (self.childViewControllers.count > 0) {
        // 统一设置返回按钮
        viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"btn_back_n"] style:0 target:self action:@selector(back)];
        viewController.hidesBottomBarWhenPushed = YES;
    }
    
    [super pushViewController:viewController animated:animated];
    
    if (viewController.view.tag == 666) {
        viewController.view.tag = 888;
        DZYMiddleView *middleView = [DZYMiddleView middleView];
        
        middleView.middleClickBlock = [DZYMiddleView shareInstance].middleClickBlock;
        middleView.isPlaying = [DZYMiddleView shareInstance].isPlaying;
        middleView.middleImg = [DZYMiddleView shareInstance].middleImg;
        
        CGRect frame = middleView.frame;
        frame.size.width = 65;
        frame.size.height = 65;
        CGSize screenSize = [UIScreen mainScreen].bounds.size;
        frame.origin.x = (screenSize.width - 65) * 0.5;
        frame.origin.y = screenSize.height - 65;
        middleView.frame = frame;
        [viewController.view addSubview:middleView];
        
    }
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    // 如果根控制器也要返回手势有效, 就会造成假死状态
    // 所以, 需要过滤根控制器
    if (self.childViewControllers.count == 1) {
        return NO;
    }
    return YES;
}

@end
